<template>
  <div>
    <a-form :form="form" @submit="handleSubmit" style="width:1200px;">
      <a-form-item v-bind="formItemLayout" label="头像">
        <a-upload
          name="avatar"
          listType="picture-card"
          class="avatar-uploader"
          :showUploadList="false"
          action="https://www.mocky.io/v2/5cc8019d300000980a055e76"
          :beforeUpload="beforeUpload"
          @change="handleChange"
          v-decorator="['avatar', {
            rules: [{
              required: true, message: '请选择您的头像!',
            }]
          }
        ]"
        >
          <img v-if="imageUrl" :src="imageUrl" alt="avatar" />
          <div v-else>
            <a-icon :type="loading ? 'loading' : 'plus'" />
            <div class="ant-upload-text">Upload</div>
          </div>
        </a-upload>
      </a-form-item>
      <a-form-item v-bind="formItemLayout" label="邮箱">
        <a-input v-decorator="['email', {
            rules: [{
              type: 'email', message: '这是无效的邮箱格式!',
            }, {
              required: true, message: '请输入您的邮箱!',
            }]
          }
        ]"
        />
      </a-form-item>
      <a-form-item v-bind="formItemLayout" label="地址">
        <a-input v-decorator="['address']"
          type="text"
        />
      </a-form-item> <a-form-item
      v-bind="formItemLayout"
      label="性别"  :style="{textAlign:'left'}"
    >
      <a-radio-group v-decorator="['sex',{
        rules: [{ required: true, message: '请选择您的性别!', whitespace: true }]
      }]">
        <a-radio-button value="1">
          男
        </a-radio-button>
        <a-radio-button value="0">
          女
        </a-radio-button>
        <a-radio-button value="2">
          中性
        </a-radio-button>
      </a-radio-group>
    </a-form-item>
      <a-form-item v-bind="formItemLayout">
      <span slot="label">
        昵称&nbsp;
        <a-tooltip title="你想要小伙伴们如何称呼您?">
          <a-icon type="question-circle-o" />
        </a-tooltip>
      </span>
        <a-input v-decorator="['nickname',
          {
            rules: [{ required: true, message: '请输入您的昵称!', whitespace: true }]
          }
        ]"
        />
      </a-form-item>
      <a-form-item
        v-bind="formItemLayout"
        label="联系方式"
      >
        <a-input
          v-decorator="[
          'phone'
        ]"
          style="width: 100%"
        >
        </a-input>
      </a-form-item>
      <a-form-item
        v-bind="formItemLayout"
        label="地址"
      >
        <a-auto-complete
          v-decorator="[
          'address',
        ]"
          placeholder="请输入地址"
        >
          <template slot="dataSource">
            <a-select-option
              v-for="website in autoCompleteResult"
              :key="website"
            >
              {{ website }}
            </a-select-option>
          </template>
          <a-input />
        </a-auto-complete>
      </a-form-item>
      <a-form-item
        v-bind="formItemLayout"
        label="个人简介"
      >
        <a-auto-complete
          v-decorator="[
          'introduce',
        ]"
          placeholder="请输入个人简介"
        >
          <template slot="dataSource">
            <a-select-option
              v-for="website in autoCompleteResult"
              :key="website"
            >
              {{ website }}
            </a-select-option>
          </template>
          <a-input />
        </a-auto-complete>
      </a-form-item>
      <a-form-item v-bind="tailFormItemLayout">
        <a-checkbox
          v-decorator="['agreement', {valuePropName: 'checked'}]"
        >
          我已经阅读 <a href="">
          天天要开心协议
        </a>（其实不用管）
        </a-checkbox>
      </a-form-item>
      <a-form-item v-bind="tailFormItemLayout">
        <a-button
          type="primary"
          html-type="submit"
        >
          提交
        </a-button>
      </a-form-item>
    </a-form>
  </div>
</template>

<script>
const client = new OSS.Wrapper({
  region: 'oss-cn-chengdu',//你的oss地址
  accessKeyId: 'LTAI4FpnfD6B5qyhS67J5Y4k',//你的ak
  accessKeySecret: 'gJ35cSU7oCiYlY9ZodRj7XeZhugANd',//你的secret
  //stsToken: ‘<Your securityToken(STS)>‘,//这里我暂时没用，注销掉
  bucket: 'icecream-test'//你的oss名字
});
function getBase64 (img, callback) {
  const reader = new FileReader()
  reader.addEventListener('load', () => callback(reader.result))
  reader.readAsDataURL(img)
}
export default {
  name: 'ProfileEdit',
  data () {
    return {
      confirmDirty: false,
      autoCompleteResult: [],
      formItemLayout: {
        labelCol: {
          xs: { span: 24 },
          sm: { span: 8 },
        },
        wrapperCol: {
          xs: { span: 24 },
          sm: { span: 16 },
        },
      },
      tailFormItemLayout: {
        wrapperCol: {
          xs: {
            span: 24,
            offset: 0,
          },
          sm: {
            span: 16,
            offset: 8,
          },
        },
      },
      loading: false,
      imageUrl: '',
      avatar: ''
    };
  },
  beforeCreate () {
    this.form = this.$form.createForm(this);
  },
  methods: {
    handleSubmit  (e) {
      e.preventDefault();
      this.form.validateFieldsAndScroll((err, values) => {
        if (!err) {
          console.log('Received values of form: ', values);
          values = {...values, ...{id: this.$store.getters.user_id,avatar:values.avatar.file.name}};
          this.$axios.post('/users/edit_profile', values).then(res => {
            if(res.data.ok){
              this.$message.success('编辑个人资料成功！',1,()=>{
                this.$router.push({name: 'Profile'})
              })
            }else{
              this.$message.error('提交失败！',1,()=>{
              })
            }
          }).catch(err => {
            console.error(err);
            this.$message.error('服务器出错，请稍后重试！')
          });
        }
      });
    },
    handleChange (info) {
      if (info.file.status === 'uploading') {
        this.loading = true
        return
      }
      if (info.file.status === 'done') {
        // Get this url from response in real world.
        getBase64(info.file.originFileObj, (imageUrl) => {
          this.imageUrl = imageUrl
          this.loading = false
        });
        this.upLoadToOss(info.file.originFileObj);
      }
    },
    beforeUpload (file) {
      const isJPG = file.type === 'image/jpeg' || file.type === 'image/png'
      if (!isJPG) {
        this.$message.error('You can only upload JPG or PNG file!')
      }
      const isLt2M = file.size / 1024 / 1024 < 2
      if (!isLt2M) {
        this.$message.error('Image must smaller than 2MB!')
      }
      return isJPG && isLt2M
    },
    upLoadToOss(file){
      client.multipartUpload(file.name, file).then(function (result) {
        console.log(result);
        this.avatar = result.name;
      }).catch(function (err) {
        this.$message.error('上传出错');
        console.log(err);
      });
    },
    downLoadFromOss(name){
      client.signatureUrl(name)
    }
  }
}
</script>

<style>
.ant-upload.ant-upload-select-picture-card{
  display: flex;
  justify-content: center;
  align-items: center;
}

</style>
